
'''
-----------------------------------------------------地址簇
usocket.AF_INET             = 2 - TCP / IP - IPv4
usocket.AF_INET6            = 10 - TCP / IP - IPv6
-----------------------------------------------------套接字类型
usocket.SOCK_STREAM         = 1 - TCP流
usocket.SOCK_DGRAM          = 2 - UDP数据报
usocket.SOCK_RAW            = 3 - 原始套接字
usocket.SO_REUSEADDR        = 4 - socket可重用
-----------------------------------------------------套接字选项级别
usocket.SOL_SOCKET = 4095
-----------------------------------------------------函数
'''
import socket
import network
import time
import _thread 
import struct
from machine import Pin
from machine import UART
led = Pin(22, Pin.OUT)
Out = Pin(12, Pin.OUT)

uart=UART(2,256000)
uart.init(256000,bits=8,parity=None,stop=1) # 8N1
host="192.168.1.6"# TCP/UDP客户端IP


port = 8080 #端口号
SSID="nona"
PASSWORD="456123789"
wlan=None
s=None
byteSet = [0xFD, 0xFC , 0xFB , 0xFA , 0x04 , 0x00 , 0xFF , 0x00 , 0x01 , 0x00 , 0x04 , 0x03 , 0x02 , 0x01]#配置使能
byteMODE = [0xFD, 0xFC , 0xFB , 0xFA , 0x02 , 0x00 , 0x62 , 0x00 , 0x04 , 0x03 , 0x02 , 0x01]#配置工程模式
byteSethex = bytearray(40)
byteSethex = "FD FC  FB  FA  04  00  FF  00  01  00  04  03  02  01"
byteSethex = bytearray(b'\xFD\xFC\xFB\xFA\x04\x00\xFF\x00\x01\x00\x04\x03\x02\x01')
byteModehex = bytearray(40)
byteModehex = "FD FC  FB  FA  02  00  62  00  04  03  02  01"
byteModehex = bytearray(b'\xFD\xFC\xFB\xFA\x02\x00\x62\x00\x04\x03\x02\x01') 
Light_ON_OFF = None
Dynamic_State = None
Movement0 = None
Movement1 = None
Movement2 = None
Movement3 = None
Movement4 = None
Movement5 = None
Movement6 = None
Staticdis0 = None
Staticdis1 = None
Staticdis2 = None
Staticdis3 = None
Staticdis4 = None
Staticdis5 = None
Staticdis6 = None
#-----------------------------------------------------连接WIFI
def connectWifi(ssid,passwd):
  global wlan
  wlan=network.WLAN(network.STA_IF)                 #create a wlan object
  wlan.active(True)                                 #Activate the network interface
  wlan.disconnect()                                 #Disconnect the last connected WiFi
  wlan.connect(ssid,passwd)                         #connect wifi
  
  while(wlan.ifconfig()[0]=='0.0.0.0'):
    time.sleep(1)
  return True
#-----------------------------------------------------TCP消息回调函数
def tlc_msg(msg):
    print(msg)

#-----------------------------------------------------UDP服务器
def UDPServer():
    try:
      if(connectWifi(SSID, PASSWORD) == True):              #判断WIFI是否连接
        s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  #创建socket对象 UDP模式
        s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #配置socket对象
        ip=wlan.ifconfig()[0]                               #获取本地IP
        s.bind((ip,port))                                   #绑定本地IP 指定端口
        print('network config:', ip)
        print('ESP32 UDPServer Start waiting...')
        global Light_ON_OFF 
        while True:
          data,addr=s.recvfrom(1024)                        #每次接收1024字节集
          print('received:',data,'from',addr)
          s.sendto(data,addr)                               #发送接收到的数据给发送者
          
          if data.startswith("LightOn"):
            #led.on() 
            Light_ON_OFF = 1
          if data.startswith("LightOff") == True:  
            #led.off()
            Light_ON_OFF = 0
          if data.startswith("LightFollow"):
            Light_ON_OFF = 2
          #print('received:',Light_ON_OFF)
    except:
      if (s):
        s.close()
      wlan.disconnect()
      wlan.active(False)


def LEDlink():
  global Light_ON_OFF  
  while True:
      time.sleep(1)
      led.on()
      time.sleep(1)
      led.off()      
      print("Light_ON_OFF",Light_ON_OFF)
      if Light_ON_OFF == 1:
        
        Out.on() #开
        print("Out on")
      elif Light_ON_OFF == 0:
        
        Out.off()#关
        print("Out off")
       

        
def Usart():
  global Movement0  
  global Movement1  
  global Movement2  
  global Movement3  
  global Movement4  
  global Movement5  
  global Movement6  
  global Staticdis0  
  global Staticdis1  
  global Staticdis2  
  global Staticdis3  
  global Staticdis4  
  global Staticdis5  
  global Staticdis6  
  #y = bytes.fromhex(byteSet)
  print("byteSet",byteSet)
  uart.write("hello")
  uart.write(byteSethex)
  time.sleep(1)
  uart.write(byteModehex)
  
  
  while True:
    request = bytearray(40)
    cmd=uart.readinto(request)
    #flag = uart.any()
    if cmd != None:
       #request=request.decode()
        if len(request) >= 37:
          if request[0] == 0xF4:
            State = request[8]
            Staticdi = request[9]*256 + request[10]
            Static = request[11]
            Movement0 = request[17]
            Movement1 = request[18]
            Movement2 = request[19]
            Movement3 = request[20]
            Movement4 = request[21]
            Movement5 = request[22]
            Movement6 = request[23]
            Staticdis0 = request[24]
            Staticdis1 = request[25]
            Staticdis2 = request[26]
            Staticdis3 = request[27]
            Staticdis4 = request[28]
            Staticdis5 = request[29]
            Staticdis6 = request[30]
            
            #print("get State from uart:",State)
            
            
            '''
            print("get request from uart:",request)
            print("it's length: ",len(request))
            print("get Movement0 from uart:",Movement0)
            print("get Movement2 from uart:",Movement2)
            print("get Staticdis0 from uart:",Staticdis0)
            
            Movement = ( Movement2 +Movement3 +Movement4+Movement5+Movement6)/5
            if Movement >= 50 :
              Out.on()
              led.off()
              print("Out on")
            else:
              Out.off()
              led.on()
              print("Out off")
              #print("get request from uart:",request)
              #print("it's length: ",len(request))
            '''
def DyState():
  while True:
    
    time.sleep(3)
    print("Movement0",Movement0 )
    print("Movement1",Movement1 )
    print("Movement2",Movement2 )
    print("Movement3",Movement3 )
    print("Movement4",Movement4 )
    print("Movement5",Movement5 )
    print("Movement6",Movement6 )
    

    print("Staticdis0",Staticdis0 )
    print("Staticdis1",Staticdis1 )
    print("Staticdis2",Staticdis2 )
    print("Staticdis3",Staticdis3 )
    print("Staticdis4",Staticdis4 )
    print("Staticdis5",Staticdis5 )
    print("Staticdis6",Staticdis6 )
    
    #静止状态判断
    if Light_ON_OFF == 2:
      
      if Movement1 != None:
        if ((Movement1 < 30) and (Movement2 < 30) and (Movement3 < 30) and (Movement4 < 30) and (Movement5 < 30) and (Movement6 < 30)):
          if ((Staticdis1 < 50) and (Staticdis2 < 50) and (Staticdis3 < 50) and (Staticdis4 < 50) and (Staticdis5 < 50) and (Staticdis6 < 50)):
            Dynamic_State = 0 
            Out.off()
            
            print("DyState",Dynamic_State )
        #微动状态判断
        
        elif ((Staticdis1 > 50) or (Staticdis2 > 50) or (Staticdis3 > 50) or (Staticdis4 > 50) or (Staticdis5 > 50) or (Staticdis6 > 50)):
            Dynamic_State = 1 
            Out.on()
            
            print("DyState",Dynamic_State )
        #移动状态判断
        elif ((Movement1 > 50) or (Movement2 > 50) or (Movement3 > 50) or (Movement4 > 50) or (Movement5 > 50) or (Movement6 > 50)):
          if ((Staticdis1 > 50) or (Staticdis2 > 50) or (Staticdis3 > 50) or (Staticdis4 > 50) or (Staticdis5 > 50) or (Staticdis6 > 50)):
            Dynamic_State = 2 
            Out.on()
            
            print("DyState",Dynamic_State )

    
if __name__ == '__main__':
    
    _thread.start_new_thread(UDPServer,())  
    _thread.start_new_thread(LEDlink,())  
    _thread.start_new_thread(Usart,())
    _thread.start_new_thread(DyState,())
    
#     tcpServer()# TCP服务端
#     tcpClient()# TCP客户端
#      UDPServer()#UDP服务端
#     UDPClient()#UDP客户端

